<template>
    <el-main v-loading="loading">
        <div class="margin_bottom_30 flex">
            <div class="searchStyle">
                <el-input class="searchStyle_action" placeholder="红包名称" size="small" v-model="filterData.redPacketName"></el-input>
            </div>
            <div class="searchStyle">
                <el-select
                    class="searchStyle_action"
                    v-model="filterData.redPacketType"
                    placeholder="请选择商品分类"
                    size="small"
                    @change="checkCategory">
                    <el-option
                        v-for="item in redPacketList"
                        :key="item.labelId"
                        :label="item.labelText"
                        :value="item.labelId"></el-option>
                </el-select>
            </div>
            <div style="margin-left: 30px">
                <el-button type="primary" size="small" @click="search">搜 索</el-button>
                <el-button size="small" @click="resetQuery">重 置</el-button>
                <el-button type="primary" size="small" @click="handleActionPage">新增红包</el-button>
            </div>
        </div>
        <el-table
            :data="dataList"
            border
            :row-key="row => row.redPacketUid"
            height="640"
            :header-cell-style="{background:'#afafaf',color:'#606266'}"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
        >
            <el-table-column align="center" type="selection" reserve-selection width="40"></el-table-column>
            <el-table-column prop="redPacketCoverUrl" align="center" width="150" label="红包封面">
                <template slot-scope="scope">
				    <img v-image-preview :src="scope.row.redPacketCoverUrl" width="60" />
			    </template>
            </el-table-column>
            <el-table-column prop="sourceInfo" align="center" width="200" label="红包名称">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.redPacketName">
                       <p>{{scope.row.redPacketName | controlLength}}</p>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column align="center" width="200" label="红包金额">
                <template slot-scope="scope">
                    <span class="text-price">{{$util.prices(scope.row.redPacketAmount)}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="sourceInfo" align="center"  label="操作" width="200">
                <template slot-scope="scope">
                    <el-button v-if="!scope.row.status" type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                    <el-button type="text" v-if="!scope.row.status" @click="handleDel(scope.row)" size="small">删除</el-button>
                    <!-- <template v-if="scope.row.status === 1">
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">下架</el-button>
                    </template>
                    <template v-else>
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">上架</el-button>
                    </template> -->
                </template>
            </el-table-column>
        </el-table>

        <el-row class="footer">
            <el-col :span="12">
				<el-checkbox
                    v-model="checkAll"
                    :disabled="!dataList.length"
                    @change="handleCheckAllChange">全选
                </el-checkbox>
			</el-col>
			<el-col :span="12">
                 <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-size="10"
                    background
                    class="text_align_right"
                    :disabled="!dataList.length"
                    :total="count"
                    layout="total, prev, pager, next, jumper">
                </el-pagination>
			</el-col>
		</el-row>
      
		<el-dialog
            :title="!redPacketInfo.redPacketUid ? '添加红包' : '编辑红包'"
            @close="handleCloseAction"
            :visible.sync="showActionPage"
            destroy-on-close
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            width="40%">
			<redPacket-action
                ref="templateRef"
                :infoData="redPacketInfo"
                :storeList="storeList"
                @func="closeTemplatePage"
                :redPacketList="redPacketList"></redPacket-action>
		</el-dialog>
    </el-main>
</template>
<script>
    import redPacketAction from './redPacket/action.vue';
    import {
        redPacket,
        deletePacket,
        merchantList,
        updateGoodsState
    } from "@/api/table";
    import utils from '@/utils/utils';

    export default {
        name: "GOODS_LIST",
        filters: {
            controlLength: curStr => utils.controlLength(curStr, 15),
        },
        data() {
            return {
                count: 0,
                checkAll: false, // 全选
                redPacketList: [{
                    labelText: '固定红包',
                    labelId: 0
                }, 
                // {
                //     labelText: '自定义红包',
                //     labelId: 1
                // }, {
                //     labelText: '随机红包',
                //     labelId: 2
                // }
                ], // 红包分类
                dataList: [],
                storeList: [], // 商户
                loading: true,
                page: 1,
                showActionPage: false,
                redPacketInfo: {},
                filterData: {
                    redPacketType: 0
                },
            }
        },
        components: {
            redPacketAction
        },
        mounted() {
            Promise.all([
                this.getData(),
                this.getMerchantList()
            ])
        },
        methods: {
            // 商户列表
            getMerchantList() {
                merchantList().then(res => {
                    if (res.data.isSuccessful === "Y") {
                        this.storeList = res.data.data
                    }
                }).catch()
            },
            // 搜索
            search() {
                this.getData();
            },
            // 加载第几页
            handleCurrentChange(val) {
                this.page = val;
                //修改页数，重新加载
                this.getData();
            },
            // 全选
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            // 重置
            resetQuery() {
                this.filterData = {
                    redPacketType: 0
                };
                this.page = 1;
                this.getData();
            },

            handleCloseAction() {
                this.redPacketInfo = {}
            },
            // 红包分类
            checkCategory(e) {
                this.filterData.redPacketType = e;
                this.getData()
            },
            handleActionPage() {
                this.showActionPage = true
            },
            closeTemplatePage(data) {
                this.handleCloseAction()
                this.showActionPage = data.action;
                data.refresh && this.getData();
            },
            // 监听选择的内容
            handleSelectionChange(val) {
                this.checkAll = this.dataList.length === val.length
            },
            // 获取数据
            getData() {
                this.loading = true;
                redPacket({
                    ...this.filterData,
                    page: this.page - 1
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const {
                            count,
                            redPacketList,
                        } = res.data.data;
                        this.count = count;
                        this.dataList  = redPacketList;
                    }
                })
                .catch(() => {})
                .finally(() => {
                    if (this.loading) {
                        this.loading = false
                    }
                });
            },
            // 编辑
            handleEdit(info) {
                this.redPacketInfo = info;
                this.handleActionPage();
                // 同步数据
				this.$nextTick(() => {
					this.$refs.templateRef.updateData()
				})
            },
            // 更改商品状态
            handleUpdate(info) {
                this.$confirm( `是否${info.status !== 1 ? '上架' : '下架'}该商品?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                     let status = info.status !== 1 ? 1 : 2;
					updateGoodsState({
                        redPacketUid: info.redPacketUid,
                        status
                    }).then(res => {
                        if(res.data.isSuccessful !== "Y"){
                            this.$message.error(res.data.message);
                            return
                        }

                        this.$message.success(res.data.message);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch();
            },
            // 删除
            handleDel(info) {
                this.$confirm("删除操作，是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
					deletePacket({
                        redPacketUid  : info.redPacketUid,
                    }).then(result => {
                        if(result.data.isSuccessful !== "Y"){
                            this.$message.error(result.data.message);
                            return
                        }

                        this.$message.success(result.data.message);
                        this.dataList = this.dataList.filter(item => item.redPacketUid !== info.redPacketUid);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch(() => {
					this.$message({
						type: "info",
						message: "已取消移除"
					});
				});
            },
        }
    }
</script>
<style lang="scss" scoped>
    .searchStyle{
        display: flex;
        align-items: center;
        font-size: 14px;
        margin: 0 20px;
        &_action {
            width: auto;
        }
    }
</style>
